/**
 * 内容生成器组件
 * 管理和展示分段内容生成过程
 */

import React, { useState, useCallback } from 'react'
import {
  Card,
  Button,
  Typography,
  Space,
  Progress,
  Alert,
  Collapse,
  Tag,
  Tooltip,
  Modal,
  Spin,
  Empty
} from 'antd'
import {
  PlayCircleOutlined,
  ReloadOutlined,
  EyeOutlined,
  CopyOutlined,
  ExportOutlined,
  CheckCircleOutlined,
  LoadingOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons'
import { 
  ArticleOutline, 
  OutlineSection, 
  ContentGenerationState, 
  SectionStatus 
} from '../../../types/spark'

const { Text, Paragraph } = Typography
const { Panel } = Collapse

export interface ContentGeneratorProps {
  outline: ArticleOutline
  generationState: ContentGenerationState
  onGenerateSection: (sectionId: string) => void
  onRegenerateSection: (sectionId: string) => void
  onGenerateAll: () => void
  onContentGenerated?: (content: string) => void
  isGenerating?: boolean
}

const ContentGenerator: React.FC<ContentGeneratorProps> = ({
  outline,
  onGenerateSection,
  onRegenerateSection,
  onGenerateAll,
  onContentGenerated,
  isGenerating = false
}) => {
  const [previewSection, setPreviewSection] = useState<OutlineSection | null>(null)
  const [isPreviewVisible, setIsPreviewVisible] = useState(false)
  const [expandedSections, setExpandedSections] = useState<string[]>([])

  // 计算统计信息
  const stats = {
    totalSections: outline.sections.length,
    completedSections: outline.sections.filter(s => s.status === SectionStatus.COMPLETED).length,
    generatingSections: outline.sections.filter(s => s.status === SectionStatus.GENERATING).length,
    errorSections: outline.sections.filter(s => s.status === SectionStatus.ERROR).length,
    totalWords: outline.sections
      .filter(s => s.content)
      .reduce((sum, s) => sum + (s.content?.length || 0), 0)
  }

  const progress = stats.totalSections > 0 ? Math.round((stats.completedSections / stats.totalSections) * 100) : 0
  const isAllCompleted = stats.completedSections === stats.totalSections && stats.totalSections > 0

  // 处理内容预览
  const handlePreviewSection = (section: OutlineSection) => {
    setPreviewSection(section)
    setIsPreviewVisible(true)
  }

  // 复制内容到剪贴板
  const handleCopyContent = async (content: string) => {
    try {
      await navigator.clipboard.writeText(content)
      // 这里可以添加成功提示
    } catch (error) {
      console.error('复制失败:', error)
    }
  }

  // 导出完整文章
  const handleExportAll = () => {
    const fullContent = outline.sections
      .sort((a, b) => a.order - b.order)
      .filter(section => section.content && section.content.trim().length > 0)
      .map(section => {
        const title = section.type === 'intro' ? '' : `## ${section.title}\n\n`
        return title + section.content
      })
      .join('\n\n')
      .trim()

    if (fullContent && onContentGenerated) {
      onContentGenerated(fullContent)
    }
  }

  // 获取段落状态显示
  const getSectionStatusDisplay = (section: OutlineSection) => {
    switch (section.status) {
      case SectionStatus.PENDING:
        return {
          icon: <ExclamationCircleOutlined style={{ color: '#faad14' }} />,
          text: '待生成',
          color: '#faad14'
        }
      case SectionStatus.GENERATING:
        return {
          icon: <LoadingOutlined style={{ color: '#1890ff' }} />,
          text: '生成中...',
          color: '#1890ff'
        }
      case SectionStatus.COMPLETED:
        return {
          icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
          text: '已完成',
          color: '#52c41a'
        }
      case SectionStatus.ERROR:
        return {
          icon: <ExclamationCircleOutlined style={{ color: '#ff4d4f' }} />,
          text: '生成失败',
          color: '#ff4d4f'
        }
      default:
        return {
          icon: <ExclamationCircleOutlined style={{ color: '#d9d9d9' }} />,
          text: '未知状态',
          color: '#d9d9d9'
        }
    }
  }

  // 渲染段落卡片
  const renderSectionCard = (section: OutlineSection) => {
    const statusDisplay = getSectionStatusDisplay(section)
    const wordCount = section.content?.length || 0
    
    return (
      <Panel
        key={section.id}
        header={
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%' }}>
            <Space>
              {statusDisplay.icon}
              <span style={{ fontWeight: 600 }}>{section.title}</span>
              <Tag color="blue">
                {section.type === 'intro' ? '引言' : section.type === 'conclusion' ? '结论' : '正文'}
              </Tag>
            </Space>
            <Space size="small" onClick={(e) => e.stopPropagation()}>
              {wordCount > 0 && (
                <Text style={{ fontSize: 12, color: '#999' }}>
                  {wordCount} 字
                </Text>
              )}
              <Text style={{ fontSize: 12, color: statusDisplay.color }}>
                {statusDisplay.text}
              </Text>
            </Space>
          </div>
        }
        extra={
          <Space size="small" onClick={(e) => e.stopPropagation()}>
            {section.status === SectionStatus.PENDING && (
              <Tooltip title="生成内容">
                <Button
                  type="text"
                  size="small"
                  icon={<PlayCircleOutlined />}
                  onClick={() => onGenerateSection(section.id)}
                  disabled={isGenerating}
                />
              </Tooltip>
            )}
            
            {(section.status === SectionStatus.COMPLETED || section.status === SectionStatus.ERROR) && (
              <Tooltip title="重新生成">
                <Button
                  type="text"
                  size="small"
                  icon={<ReloadOutlined />}
                  onClick={() => onRegenerateSection(section.id)}
                  disabled={isGenerating}
                />
              </Tooltip>
            )}
            
            {section.content && (
              <Tooltip title="预览内容">
                <Button
                  type="text"
                  size="small"
                  icon={<EyeOutlined />}
                  onClick={() => handlePreviewSection(section)}
                />
              </Tooltip>
            )}
          </Space>
        }
      >
        <div style={{ padding: '8px 0' }}>
          {/* 段落描述 */}
          {section.description && (
            <Paragraph style={{ marginBottom: 12, fontSize: 13, color: '#666' }}>
              {section.description}
            </Paragraph>
          )}

          {/* 关键要点 */}
          {section.keyPoints.length > 0 && (
            <div style={{ marginBottom: 12 }}>
              <Text strong style={{ fontSize: 12, color: '#333' }}>关键要点：</Text>
              <div style={{ marginTop: 4 }}>
                {section.keyPoints.map((point, index) => (
                  <Tag key={index} style={{ fontSize: 11, marginBottom: 2 }}>
                    {point}
                  </Tag>
                ))}
              </div>
            </div>
          )}

          {/* 生成的内容预览 */}
          {section.content ? (
            <div className="section-content-preview">
              <Text style={{ fontSize: 13, lineHeight: 1.6 }}>
                {section.content.substring(0, 200)}
                {section.content.length > 200 && '...'}
              </Text>
              <div style={{ marginTop: 8, textAlign: 'right' }}>
                <Space size="small">
                  <Button
                    size="small"
                    icon={<EyeOutlined />}
                    onClick={() => handlePreviewSection(section)}
                  >
                    查看全文
                  </Button>
                  <Button
                    size="small"
                    icon={<CopyOutlined />}
                    onClick={() => handleCopyContent(section.content || '')}
                  >
                    复制
                  </Button>
                </Space>
              </div>
            </div>
          ) : (
            <div className="section-content-empty">
              {section.status === SectionStatus.GENERATING ? (
                <Spin size="small">
                  <div style={{ padding: 20 }}>正在生成内容...</div>
                </Spin>
              ) : (
                <div style={{ padding: 20, color: '#999' }}>
                  暂无内容，点击"生成内容"开始创作
                </div>
              )}
            </div>
          )}
        </div>
      </Panel>
    )
  }

  return (
    <div className="content-generator">
      {/* 头部统计和操作 */}
      <Card style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          {/* 统计信息 */}
          <div style={{ display: 'flex', gap: 24 }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 20, fontWeight: 600, color: '#1890ff' }}>
                {stats.completedSections}/{stats.totalSections}
              </div>
              <div style={{ fontSize: 12, color: '#999' }}>段落完成</div>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 20, fontWeight: 600, color: '#52c41a' }}>
                {stats.totalWords.toLocaleString()}
              </div>
              <div style={{ fontSize: 12, color: '#999' }}>总字数</div>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 20, fontWeight: 600, color: '#ff6b35' }}>
                {progress}%
              </div>
              <div style={{ fontSize: 12, color: '#999' }}>完成进度</div>
            </div>
          </div>

          {/* 操作按钮 */}
          <Space>
            <Button
              type="primary"
              icon={<PlayCircleOutlined />}
              onClick={onGenerateAll}
              disabled={isGenerating || isAllCompleted}
              loading={isGenerating}
            >
              {isGenerating ? '生成中...' : '生成全部'}
            </Button>
            
            {isAllCompleted && (
              <Button
                type="primary"
                icon={<ExportOutlined />}
                onClick={handleExportAll}
              >
                导入编辑器
              </Button>
            )}
          </Space>
        </div>

        {/* 进度条 */}
        <div style={{ marginTop: 16 }}>
          <Progress
            percent={progress}
            status={stats.errorSections > 0 ? 'exception' : isGenerating ? 'active' : 'normal'}
            strokeColor={{
              '0%': '#108ee9',
              '100%': '#87d068',
            }}
          />
        </div>
      </Card>

      {/* 状态提示 */}
      {stats.errorSections > 0 && (
        <Alert
          message={`${stats.errorSections} 个段落生成失败`}
          description="请检查网络连接或AI配置，然后重新生成失败的段落。"
          type="warning"
          showIcon
          style={{ marginBottom: 16 }}
          action={
            <Button size="small" onClick={onGenerateAll}>
              重试全部
            </Button>
          }
        />
      )}

      {isAllCompleted && (
        <Alert
          message="所有段落已生成完成"
          description="您可以预览各段落内容，或直接导入到编辑器中继续编辑。"
          type="success"
          showIcon
          style={{ marginBottom: 16 }}
          action={
            <Button type="primary" size="small" onClick={handleExportAll}>
              导入编辑器
            </Button>
          }
        />
      )}

      {/* 段落生成列表 */}
      <Card title="文章段落" size="small">
        {outline.sections.length === 0 ? (
          <Empty description="暂无段落数据" />
        ) : (
          <Collapse
            activeKey={expandedSections}
            onChange={(keys) => setExpandedSections(keys as string[])}
            ghost
          >
            {outline.sections
              .sort((a, b) => a.order - b.order)
              .map(renderSectionCard)}
          </Collapse>
        )}
      </Card>

      {/* 内容预览模态框 */}
      <Modal
        title={previewSection?.title}
        open={isPreviewVisible}
        onCancel={() => setIsPreviewVisible(false)}
        footer={[
          <Button
            key="copy"
            icon={<CopyOutlined />}
            onClick={() => {
              if (previewSection?.content) {
                handleCopyContent(previewSection.content)
              }
            }}
          >
            复制内容
          </Button>,
          <Button key="close" onClick={() => setIsPreviewVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {previewSection?.content ? (
          <div style={{ 
            maxHeight: 500, 
            overflowY: 'auto',
            padding: 16,
            background: '#fafafa',
            borderRadius: 6,
            fontSize: 14,
            lineHeight: 1.8,
            whiteSpace: 'pre-wrap'
          }}>
            {previewSection.content}
          </div>
        ) : (
          <Empty description="暂无内容" />
        )}
      </Modal>
    </div>
  )
}

export default ContentGenerator